/**
 * Created by liguangsong on 16/8/15.
 */
$(document).ready(function() {
    getGoodsInfo();
});


function getGoodsInfo() {

    $.ajax({
        url: '/ajax_goodsInfo/',
        success: function (result) {
            var goodsInfoDic = {
                "goodsInfo": result
            }
            showGoodsInfo(goodsInfoDic);
            bindButtonClickEvent(result);
        },
        error: function (result) {

            alert(result);
        }
    });
}


function showGoodsInfo(goods) {
    var goodsTemplate = $("#goods_template").html();
    Mustache.parse(goodsTemplate);
    var goodsInfo = Mustache.render(goodsTemplate, goods);
    $(".goods_info thead").after(goodsInfo);

}


function getTransInfo(good){
    dict = { 'id': good.id, 'type': good.type, 'name': good.name, 'unit': good.unit, 'discount': good.discount, 'price': good.price, 'change': false };
    dict.compute = 1;
    return dict;
}

function bindButtonClickEvent(goods) {
    $("tr button").click(function() {
        var id = this.id;
        var sameIndex = searchSameGoodIndex(goods, id);
        var good = goods[sameIndex];
        good = getTransInfo(good)
        console.log(good)
        $.post('/ajax_setShopping/', good, function(result){
            modifyShopCarNumber();
        })   
     
    });
}


function searchSameGoodIndex(shopGood , id) {
    for (var i = 0; i < shopGood.length; i++) {
        if (shopGood[i]["id"] == id) {
            return i;
        }
    }
    return shopGood.length;
}


function getSubtotalPrice(info) {
    var number = info["count"];
    var price = number * info["price"];
    if (number > 2 && info["discount"]==true) {
        number = info["count"] - parseInt(info["count"] / 3);
        var realPrice = number * info["price"];
        return realPrice + "元(原价：" + price + "元)";
    }
    else {
        return price + "元";
    }
}





